<template>
 <div class="addgrade_container">
    <Row>
      <Col span="24">
        <div class="nav">
            <h3 class="addcustomergroup_title">等级设置</h3>
        </div>
      </Col>
  </Row>
  <div class="form_container">
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80" label-position="left">
        <div>
            <h3 class="title">等级信息</h3>
            <FormItem label="等级:" prop="levelId" :label-width="80" style="margin-top:1vh;padding-left:4vw;">
                <Input v-model="formValidate.levelId" placeholder="请注意，您设置的等级须按照从低到高(1-10)依次增加" style="width:300px;" clearable></Input>
            </FormItem>
            <FormItem label="等级名称:" prop="levelName" :label-width="80" style="margin-top:3vh;padding-left:4vw;">
                <Input v-model="formValidate.levelName" placeholder="请输入等级名称, 最多不超过5个字" style="width:300px;" clearable :maxlength=5></Input>
            </FormItem>
            <FormItem label="等级描述:" prop="levelDescription" :label-width="80" style="margin-top:3vh;padding-left:4vw;">
                <Input v-model="formValidate.levelDescription" type="textarea" :autosize="{minRows: 2,maxRows: 5}" :maxlength=100 placeholder="请输入等级描述, 最多不超过100个字" style="width:300px;" clearable></Input>
            </FormItem>
        </div>
        <div style="margin-top:1vh;">
            <h3 class="title">升级规则</h3>
            <FormItem label="升级条件:" prop="consumeCount" :label-width="80" style="margin-top:1vh;padding-left:4vw;">
                <span>累计消费次数满</span>
                <Input v-model="formValidate.consumeCount" placeholder="请输入次数" style="width:150px;" clearable></Input>
                <span>次</span>
                <span class="text">或</span>
            </FormItem>
            <FormItem prop="consumeAmount" :label-width="80" style="margin: 2vh 0vh 0vh 7.8vh">
                <span>累计消费金额满</span>
                <Input v-model="formValidate.consumeAmount" placeholder="请输入金额" style="width:150px;" clearable></Input>
                <span>元</span>
            </FormItem>
            <FormItem label="等级有效期:" :label-width="80" style="margin-top:2vh;padding-left:4vw;">
                <RadioGroup v-model="formValidate.effectiveDateType" vertical>
                    <Radio label="0"> 一直有效</Radio>
                    <Radio label="1">
                        滚动有效期
                        <Input v-model="formValidate.effectiveDays" placeholder="请输入天数" style="width:150px;" clearable></Input>
                        <span>天后过期</span>
                    </Radio>
                    <Radio label="2" style="margin-top:1vh; float: left;">
                      固定日期过期
                    </Radio>
                  <div style="float: left; margin-top: 1vh">
                    <Select v-model="formValidate.effectiveYears" placeholder="请选择年份" style="width: 200px" clearable>
                      <Option v-for="item in yearlist" :value="item.value" :key="item.value">{{item.label}}</Option>
                    </Select>
                    <DatePicker type="datetime" v-model="formValidate.effectiveDate" format="MM-dd" placeholder="请选择日期" style="width: 200px"></DatePicker>
                    <span>失效</span>
                  </div>

                </RadioGroup>
            </FormItem>
        </div>
        <div style="margin-top:1vh;">
            <h3 class="title">保级设置</h3>
            <FormItem label="是否支持保级:" :label-width="88" style="margin-top:1vh;padding-left:4vw;">
                <i-switch v-model="formValidate.supportMaintenance" size="large">
                    <span slot="open">开</span>
                    <span slot="close">关</span>
                </i-switch>
            </FormItem>
            <FormItem label="保级条件:" :label-width="80" style="margin-top:2vh;padding-left:4vw;">
               <span>在有效期内累计消费次数满</span>
               <Input v-model="formValidate.maintenanceConsumeCount" placeholder="请输入消费次数" style="width:150px;" clearable></Input>
               <span>次</span>
               <span class="text">或</span>
            </FormItem>
            <FormItem style="margin:1vh 0px 0px 4vw;">
               <span>累计消费金额满</span>
               <Input v-model="formValidate.maintenanceConsumeAmount" placeholder="请输入消费金额" style="width:150px;" clearable></Input>
               <span>元则可以成功保级</span>
            </FormItem>
        </div>

        <div style="margin-top:1vh;">
            <h3 class="title">降级设置</h3>
            <FormItem label="是否支持降级:" :label-width="88" style="margin-top:1vh;padding-left:4vw;">
                <i-switch v-model="formValidate.supportDowngrade" size="large">
                    <span slot="open">开</span>
                    <span slot="close">关</span>
                </i-switch>
            </FormItem>
            <FormItem label="降级条件:" :label-width="80" style="margin-top:1vh;padding-left:4vw;">
                <span>到期降级至</span>
                <Select v-model="formValidate.downgradeLevelId" placeholder="请选择等级" style="width: 200px" clearable>
                    <Option v-for="item in gradelist" :value="item.levelId" :key="item.levelId">{{item.levelName}}</Option>
                </Select>
            </FormItem>
        </div>
        <Row type="flex" justify="center" style="margin-top:1vh;">
            <Col>
                <FormItem>
                    <Button style="margin-left: 8px" @click.prevent="returnTable()">返回</Button>
                    <Button type="primary" @click="handleSubmit('formValidate')">保存</Button>
                </FormItem>
            </Col>
        </Row>
    </Form>
  </div>
 </div>
</template>
<script>
import { fetchgradeList, savegrade, getLevelRuleById } from '@/api/grade';
export default {
    name: "Addgrade",
    data(){
      const validateNumber = (rule, value, callback) => {
        if (value % 1 != 0) {
          callback(new Error("请输入整数"));
        } else {
          callback();
        }

      };
      const existsLevelId = (rule, value, callback) => {
        var existsLevelIdBoolean = false;
        this.gradelist.forEach(item =>{
          if (this.formValidate.levelId == item.levelId){
            existsLevelIdBoolean = true;
          }
        })
        if (this.oldLevleId == this.formValidate.levelId){
          existsLevelIdBoolean = false;
        }
        if (existsLevelIdBoolean) {
          callback(new Error("等级已存在，请重新输入"));
        } else {
          callback();
        }
      }
        return {
          gradeId:this.$route.params.id,
          oldLevleId: '',
          yearlist:[
              {
                  label:'1年',
                  value:'1',
              },
              {
                  label:'2年',
                  value:'2',
              }
          ],
          gradelist:[],
          formValidate: {
            id:0,
            levelId: '',
            levelName: '',
            levelDescription:'',
            consumeCount:'',
            consumeAmount:'',
            effectiveDateType: '0',
            effectiveDays:'',
            effectiveYears:'',
            effectiveDate:'',
            supportMaintenance:false,//是否支持保级
            maintenanceConsumeCount:'',
            maintenanceConsumeAmount:'',
            supportDowngrade:false,//是否支持降级
            downgradeLevelId: 0,
          },
          ruleValidate: {
            levelId: [
              { required: true, message: '请输入等级', trigger: 'blur' },
              { validator: validateNumber , message: "请输入数字", trigger: "blur", transform(value){return Number(value);}},
              { validator: existsLevelId , message: "等级已存在，请重新输入", trigger: "blur", transform(value){return Number(value);}}
            ],
            levelName: [
                { required: true, message: '请输入等级名称', trigger: 'blur' }
              ],
            levelDescription: [
                { required: true, message: '请输入等级描述', trigger: 'blur' }
              ],
            consumeCount: [
                { required: true, message: '请输入消费次数', trigger: 'blur' },
                { validator: validateNumber , message: "请输入数字", trigger: "blur", transform(value){return Number(value);}}
              ],
            consumeAmount: [
                { required: true, message: '请输入消费金额', trigger: 'blur' },
                { validator: validateNumber , message: "请输入数字", trigger: "blur", transform(value){return Number(value);}}
              ]
            }
        } 
    },
    methods:{
      crtTimeFtt(val) {
        if (val != null) {
          var date = new Date(val);
          return (date.getMonth() + 1) + '-' + date.getDate();
        }
      },
      FetchgradeList () {  // 查询
        this.TableLoading = true;
        var res = {};
        fetchgradeList().then((res)=>{
          this.TableLoading = false;
          if(res.data.code == 200){
            this.gradelist = res.data.data;
          }
        })
          .catch(error=>{
            this.$Message.error("操作失败【" + error + "】");
          })
      },
      handleSubmit (name) {

        this.$refs[name].validate((valid) => {
          if (valid) {
             var reqParams = this.formValidate;
             if (this.formValidate.supportMaintenance){
               reqParams.supportMaintenance = 1;
             }else {
               reqParams.supportMaintenance = 0;
             }
            if (this.formValidate.supportDowngrade){
              reqParams.supportDowngrade = 1;
            }else {
              reqParams.supportDowngrade = 0;
            }

            if (this.formValidate.effectiveDate){
              reqParams.effectiveDate = this.crtTimeFtt(this.formValidate.effectiveDate);
            }
             savegrade(reqParams).then((res)=>{
                 if(res.data.code == 200){
                   this.$router.push({path:'/loyalty/gradesetting'})
                   this.$Message.success('保存成功！')
                 }
             }).catch((error) => {
               this.$Message.error("保存失败【" + error + "】");
             });
          }
        })
      },
      returnTable() {
          this.$router.back(-1)
      },
      //编辑加载数据
      getLevelRuleById(){
        if (this.gradeId){
          getLevelRuleById(this.gradeId).then(res=>{
            if (res.data.code == 200) {
              this.formValidate = res.data.result;
              if (res.data.result){
                if (res.data.result.supportMaintenance == 1){
                  this.formValidate.supportMaintenance = true;
                }else {
                  this.formValidate.supportMaintenance = false;
                }
                if (res.data.result.supportDowngrade == 1){
                  this.formValidate.supportDowngrade = true;
                }else {
                  this.formValidate.supportDowngrade = false;
                }
                if (res.data.result.effectiveDateType != null){
                  this.formValidate.effectiveDateType = res.data.result.effectiveDateType.toString();
                }
                if (res.data.result.levelId != null){
                  this.formValidate.levelId = res.data.result.levelId.toString();
                }
                if (res.data.result.consumeCount != null){
                  this.formValidate.consumeCount = res.data.result.consumeCount.toString();
                }
                if (res.data.result.consumeAmount != null){
                  this.formValidate.consumeAmount = res.data.result.consumeAmount.toString();
                }
                if (res.data.result.effectiveYears != null){
                  this.formValidate.effectiveYears = res.data.result.effectiveYears.toString();
                }
                this.oldLevleId = res.data.result.levelId;
              }
            }
          }).catch(error=>{
            this.$Message.error("操作失败【" + error + "】");
          })
        }
      },

      searchLevelId(){

      }

    },
  mounted () {
    this.FetchgradeList();
    this.getLevelRuleById();

  }
}     
</script>
<style lang="scss" scoped>
@import "../../styles/common";
.addgrade_container{
  background-color: #fff;
  .nav {
    height: 5vh;
    padding-left: 1vw;
    line-height: 35px;
    .addcustomergroup_title {
      font-size: 1.1rem;
      font-family: Times;
      font-weight: bolder;
    }
  }
  .form_container{
      margin-top: 2vh;
    .title{
        font-size: 1.1rem;
        font-weight: bolder;
        @include Integral_title_global;
    }
  }
 
}
</style>
